'use strict';

const Service = require('egg').Service;
const qiniu = require('qiniu');

class FileService extends Service {
  constructor(ctx) {
    super(ctx);
    const { accessKey, secretKey } = this.config.thirdParty.qiniu;
    this.mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
    this.bucketManager = new qiniu.rs.BucketManager(this.mac, new qiniu.conf.Config());
  }
  // 生成私有下载链接
  generatePrivateDownloadUrl(fileType, hash, processStyle) {
    const { domains } = this.config.thirdParty.qiniu;
    // 设置过期时间为两个小时后
    const deadline = parseInt(Date.now() / 1000) + 7200;
    return this.bucketManager.privateDownloadUrl(
      domains[fileType],
      `${hash}${processStyle ? `-${processStyle}` : ''}`,
      deadline
    );
  }
  // 生成上传凭证
  generateUploadToken() {
    console.log('this', this);
    const { bucket } = this.config.thirdParty.qiniu;
    const options = {
      scope: bucket,
    };
    const putPolicy = new qiniu.rs.PutPolicy(options);
    return putPolicy.uploadToken(this.mac);
  }
  // 记录
  async record(type, hash) {
    return await this.ctx.model.File.findOrCreate({
      defaults: { hash, type },
      where: { hash },
    });
  }
  // 批量记录
  bulkRecord(type, hashes) {
    const promises = [];
    for (let i = 0; i < hashes.length; i++) {
      promises.push(this.record(type, hashes[i]));
    }
    return Promise.all(promises);
  }
}

module.exports = FileService;
